package com.bos.utils;

import org.apache.commons.logging.Log;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.internal.CriteriaImpl;

import java.lang.reflect.Field;
import java.util.ArrayList;

/**
 * @author Administrator
 * @Description hibernate的DetachedCriteria中的查询条件
 */
public class HibernateUtils {

    public static void eraseCriteria(DetachedCriteria dc) {
        try {
            Field impl = dc.getClass().getDeclaredField("impl");
            impl.setAccessible(true);

            // 得到实现类
            CriteriaImpl cimpl = (CriteriaImpl) impl.get(dc);

            // 思路二: 再次反射, 直接将criterionEntries置空.
            // 获取criterionEntries属性
            Field criterionEntries = cimpl.getClass().getDeclaredField("criterionEntries");
            criterionEntries.setAccessible(true);
            // 重置条件list
//            criterionEntries.set(cimpl, new ArrayList());

            //或者直接清除原有的查询条件列表
            ArrayList<CriteriaImpl.CriterionEntry> criterionEntriesList = (ArrayList<CriteriaImpl.CriterionEntry>) criterionEntries.get(cimpl);
            criterionEntriesList.clear();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

    }
}
